﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNetExtensions.AspNet
{
    public class Singleton<T> : IDisposable where T : class
    {
        protected Singleton() { }

        protected static object[] mutex = new object[] { };
        protected static T _default;
        public static T Default
        {
            get
            {
                if (_default == null)
                {
                    lock (mutex)
                    {
                        if (_default == null)
                        {
                            Type type = typeof(T);
                            var ctor = type.GetConstructor(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, Type.DefaultBinder, Type.EmptyTypes, null);

                            if (ctor == null) throw new Exception($" type `{type.FullName}` miss a none paramters constructor .");

                            object instance = ctor.Invoke(null);

                            if (instance == null) throw new Exception($" type `{type.FullName}` miss a none paramters constructor .");

                            _default = (instance as T);
                        }
                    }
                }

                return _default;
            }
        }

        public static void Destroy()
        {
            _default = null;
        }

        public void Dispose()
        {
            _default = null;
        }
    }
}
